#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WMS Sample Windows服务包装器
将WMS应用包装为Windows服务运行
"""

import os
import sys
import time
import logging
import threading
from pathlib import Path

# 添加项目根目录到Python路径
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

try:
    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
except ImportError:
    print("错误: 需要安装pywin32库")
    print("请运行: pip install pywin32")
    sys.exit(1)

# 设置工作目录
if hasattr(sys, '_MEIPASS'):
    # PyInstaller打包后的临时目录
    application_path = sys._MEIPASS
else:
    # 开发环境
    application_path = os.path.dirname(os.path.abspath(__file__))

os.chdir(application_path)

# 导入路径管理器
from src.core.path_manager import path_manager

# 配置日志
log_file = path_manager.get_log_file('wms_service.log')
path_manager.ensure_dir_exists(log_file.parent)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(str(log_file), encoding='utf-8'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('WMSService')

class WMSService(win32serviceutil.ServiceFramework):
    """WMS Sample Windows服务"""
    
    _svc_name_ = "WMSSampleService"
    _svc_display_name_ = "WMS Sample 料位管理服务"
    _svc_description_ = "WMS Sample 料位管理系统后台服务"
    
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.is_running = False
        self.api_server_thread = None
        
        # 记录路径信息
        logger.info(f"服务初始化 - 部署模式: {path_manager.deployment_mode}")
        logger.info(f"应用目录: {path_manager.app_dir}")
        logger.info(f"数据目录: {path_manager.data_dir}")
        logger.info(f"配置目录: {path_manager.config_dir}")
        logger.info(f"日志目录: {path_manager.logs_dir}")
    
    def SvcStop(self):
        """停止服务"""
        logger.info("正在停止WMS Sample服务...")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        
        self.is_running = False
        win32event.SetEvent(self.hWaitStop)
        
        # 停止API服务器
        if self.api_server_thread and self.api_server_thread.is_alive():
            logger.info("正在停止API服务器...")
            # 这里可以添加优雅停止API服务器的逻辑
        
        logger.info("WMS Sample服务已停止")
    
    def SvcDoRun(self):
        """运行服务"""
        logger.info("正在启动WMS Sample服务...")
        
        try:
            # 记录服务启动事件
            servicemanager.LogMsg(
                servicemanager.EVENTLOG_INFORMATION_TYPE,
                servicemanager.PYS_SERVICE_STARTED,
                (self._svc_name_, '')
            )
            
            self.is_running = True
            
            # 初始化数据库
            logger.info("正在初始化数据库...")
            from src.models.database.database import db_manager
            logger.info("数据库初始化完成")
            
            # 启动API服务器
            logger.info("正在启动API服务器...")
            self.start_api_server()
            
            logger.info("WMS Sample服务启动成功")
            
            # 等待停止信号
            win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
            
        except Exception as e:
            logger.error(f"服务运行出错: {e}")
            import traceback
            logger.error(traceback.format_exc())
            
            # 记录服务错误事件
            servicemanager.LogErrorMsg(f"WMS Sample服务运行出错: {e}")
    
    def start_api_server(self):
        """启动API服务器"""
        def run_server():
            try:
                from src.api.api_server import app
                from src.core.config import config
                import uvicorn
                import sys
                import io
                
                # 修复PyInstaller打包环境中的stdout/stderr问题
                if sys.stdout is None:
                    sys.stdout = io.StringIO()
                if sys.stderr is None:
                    sys.stderr = io.StringIO()
                
                logger.info(f"API服务器启动在 {config.api_host}:{config.api_port}")
                
                # 使用简化的日志配置，避免formatter配置问题
                uvicorn.run(
                    app,
                    host=config.api_host,
                    port=config.api_port,
                    log_level="info",
                    access_log=False,
                    log_config=None  # 禁用默认日志配置，使用我们自己的
                )
                
            except Exception as e:
                logger.error(f"API服务器启动失败: {e}")
                import traceback
                logger.error(traceback.format_exc())
        
        self.api_server_thread = threading.Thread(target=run_server, daemon=True)
        self.api_server_thread.start()

if __name__ == '__main__':
    if len(sys.argv) == 1:
        # 没有参数时，尝试启动服务
        try:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(WMSService)
            servicemanager.StartServiceCtrlDispatcher()
        except Exception as e:
            logger.error(f"服务启动失败: {e}")
            print(f"服务启动失败: {e}")
    else:
        # 有参数时，处理服务安装/卸载等操作
        win32serviceutil.HandleCommandLine(WMSService) 